package edu.sctu.yueding.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import edu.sctu.yueding.R;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.UserBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.CompressImgUntil;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.PermissionUtil;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.MultipartRequest;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.CircleImageView;

import static com.umeng.socialize.Config.dialog;


/**
 * Created by Administrator on 2016/8/20.
 */
@SuppressLint("SdCardPath")
public class MyInfoEditInfoActivity extends BaseActivity implements View.OnClickListener {

    TextView cancelText;
    TextView finishText;
    EditText nickNameEdit;
    EditText introduceEdit;
    CircleImageView headImg;
    RelativeLayout imgRel;
    View popupWindow_view;

    String nickName;
    String introduce;
    private Button camera, gallery, cancel;

    private PopupWindow popupWindow;
    private static int CAMERA_REQUEST_CODE = 1;
    private static int GALLERY_REQUEST_CODE = 2;
    private RelativeLayout parent;
    private LinearLayout ll_popup;

    private ProgressUtil progressUtil;
    private ProgressDialog progressDialog;
    private SharePreference sharePreference;
    private CompressImgUntil compressImgUntil;
    private Bitmap compressBitmap;
    private Bitmap newBitmap = null;
    List<File> files = new ArrayList<>();
    Bitmap bt;
    String path;

    // 要申请的权限
    private String[] permissions = {Manifest.permission.CAMERA};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editmyinfo);
        initView();
        initSystemBar(this, 0);
    }

    private void initView() {

        cancelText = (TextView) findViewById(R.id.activity_editmyinfo_cancel);

        finishText = (TextView) findViewById(R.id.activity_editmyinfo_finish);
        finishText.setClickable(false);

        nickNameEdit = (EditText) findViewById(R.id.activity_editmyinfo_nametextinfo);
        introduceEdit = (EditText) findViewById(R.id.activity_editmyinfo_introducetextinfo);
        imgRel = (RelativeLayout) findViewById(R.id.activity_editmyinfo_headimg_rel);
        headImg = (CircleImageView) findViewById(R.id.activity_editmyinfo_headimg);
        progressUtil = ProgressUtil.getInstance(MyInfoEditInfoActivity.this, null);
        sharePreference = SharePreference.getInstance(this);

        nickNameEdit.addTextChangedListener(new UpdateNickNameTextWatcher());
        introduceEdit.addTextChangedListener(new UpdateIntroTextWatcher());

        nickName = SharePreference.getInstance(MyInfoEditInfoActivity.this).getString(CacheConfig.CACHE_NICKNMAE);
        introduce = SharePreference.getInstance(MyInfoEditInfoActivity.this).getString(CacheConfig.CACHE_USER_INTRODUCTION_SELF);


        path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/悦定/";
        bt = BitmapFactory.decodeFile(path + sharePreference.getString(CacheConfig.CACHE_USER_NAME) + "head.jpeg");//从Sd中找头像，转换成Bitmap
        if (bt != null) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);//转换成drawable
            headImg.setImageDrawable(drawable);
        } else {
//            headImg.setBackgroundResource(R.drawable.user_default_portrait);
        }

        compressImgUntil = CompressImgUntil.getInstance();

        nickNameEdit.setText(nickName);
        introduceEdit.setText(introduce);
        setEvent();

    }

    private void initPopupWindow(View v) {

        // TODO Auto-generated method stub
        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        popupWindow_view = getLayoutInflater().inflate(R.layout.activity_popupwindow_main, null, false);
        // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
        popupWindow = new PopupWindow(popupWindow_view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);


        // 设置动画效果
//                popupWindow.setAnimationStyle(R.style.AnimationFade);
        // 这里是位置显示方式,在屏幕的左侧
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        // 点击其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });

        ll_popup = (LinearLayout) popupWindow_view.findViewById(R.id.ll_popup);
        parent = (RelativeLayout) popupWindow_view.findViewById(R.id.parent);

        camera = (Button) popupWindow_view.findViewById(R.id.item_popupwindows_camera);
        gallery = (Button) popupWindow_view.findViewById(R.id.item_popupwindows_Photo);
        cancel = (Button) popupWindow_view.findViewById(R.id.item_popupwindows_cancel);
        camera.setOnClickListener(this);
        gallery.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }


    private void setEvent() {

        cancelText.setOnClickListener(this);
        finishText.setOnClickListener(this);
        imgRel.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_editmyinfo_cancel:

                if (newBitmap != null){
                    Log.e("555", "555");
                    sharePreference.setCache(CacheConfig.IS_UPDATE_PORTRAIT, true);
                }

                Bundle b = new Bundle();
                b.putInt("flag",3);
                JumpUtils.activityToFragmentJump(MyInfoEditInfoActivity.this, b);

                break;
//            case R.id.activity_editmyinfo_finish:
//
//                progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_SPINNER, true);
//
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        upload();
//                    }
//                }, 1000);
//                break;

            case R.id.activity_editmyinfo_headimg_rel:
                initPopupWindow(v);
                break;
            case R.id.item_popupwindows_camera:

                //先验证手机是否有sdcard
                String status = Environment.getExternalStorageState();
                if (status.equals(Environment.MEDIA_MOUNTED)) {

                    // 检查该权限是否已经获取
                    int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 如果没有授予该权限，就去提示用户请求

                        ActivityCompat.requestPermissions(this, permissions, 321);

                    } else {

                        try {
                            File dir = new File(Environment.getExternalStorageDirectory() + "/悦定/");
                            if (!dir.exists()) dir.mkdirs();

                            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            File f = new File(dir, "image.jpeg");//localTempImgDir和localTempImageFileName是自己定义的名字
                            Uri u = Uri.fromFile(f);
                            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                            startActivityForResult(intent, CAMERA_REQUEST_CODE);
                        } catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
                            Toast.makeText(MyInfoEditInfoActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
                        }

                    }




                } else {
                    Toast.makeText(MyInfoEditInfoActivity.this, "没有储存卡", Toast.LENGTH_LONG).show();
                }


                popupWindow.dismiss();
                ll_popup.clearAnimation();
                break;
            case R.id.item_popupwindows_Photo:
                Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                intent1.setType("image/*");
                startActivityForResult(intent1, GALLERY_REQUEST_CODE);
                popupWindow.dismiss();
                ll_popup.clearAnimation();

                break;
            case R.id.item_popupwindows_cancel:
                popupWindow.dismiss();
                ll_popup.clearAnimation();
                break;
        }
    }

    private void upload() {

        if (!checkIsNull(nickName, introduce)) {
            Toast.makeText(MyInfoEditInfoActivity.this, "请将信息填写完整！", Toast.LENGTH_LONG).show();
        } else {
            HashMap map = new HashMap();
            map.put("nickName", nickName);
            map.put("selfIntroduction", introduce);
            MultipartRequest multipartRequest = new MultipartRequest(URLConfig.USER_INFO,
                    errorListener,
                    listener,
                    "file",
                    files,
                    map,
                    "Bearer " + SharePreference.getInstance(MyInfoEditInfoActivity.this).getString(CacheConfig.CACHE_TOKEN));
            multipartRequest.setRetryPolicy(new DefaultRetryPolicy(120 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES
                    , DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            GetVolleyHttp.getInstance(this).uploadFiles(multipartRequest);
        }
    }

    boolean checkIsNull(String nickName, String introduce) {
        if (nickName != null && introduce != null) {
            return true;
        } else {
            return false;
        }
    }


    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String json) {

            Log.e("json000000", json);
            Bundle bundle = new Bundle();
            bundle.putInt("flag", 3);

            JsonBaseBeen<UserBean> userBeanJsonBaseBeen = JSON.parseObject(json, new TypeReference<JsonBaseBeen<UserBean>>() {
            }.getType());

            sharePreference.setCache(CacheConfig.IS_UPDATE_PORTRAIT, true);
            sharePreference.setCache(CacheConfig.CACHE_PORTRAIT_PATH, userBeanJsonBaseBeen.getData().getAvatarUrl());
            sharePreference.setCache(CacheConfig.CACHE_NICKNMAE, nickNameEdit.getText().toString());
            sharePreference.setCache(CacheConfig.CACHE_USER_INTRODUCTION_SELF, introduceEdit.getText().toString());

            JumpUtils.activityToFragmentJump(MyInfoEditInfoActivity.this, bundle);
            progressUtil.dismiss(progressDialog);
            MyInfoEditInfoActivity.this.finish();

        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            sharePreference.setCache(CacheConfig.IS_UPDATE_PORTRAIT, true);
            progressUtil.dismiss(progressDialog);
            Toast.makeText(MyInfoEditInfoActivity.this, "网络出了些小问题", Toast.LENGTH_SHORT)
                    .show();

        }
    };


    private Bitmap convertUri(Uri uri) {
        InputStream is = null;
        try {
            is = getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            assert is != null;
            is.close();
            return bitmap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        File tempFile = null;
        Uri uri = null;
        if (requestCode == CAMERA_REQUEST_CODE) {

            File f = new File(Environment.getExternalStorageDirectory()
                    + "/悦定/image.jpeg");

            Log.e("f", f.getAbsolutePath());
            try {

                uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                        f.getAbsolutePath(), null, null));

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (requestCode == GALLERY_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            uri = data.getData();
        }

        if (uri != null){
            newBitmap = convertUri(uri);

            headImg.setImageBitmap(newBitmap);
        compressBitmap = compressImgUntil.ratio(newBitmap);
        tempFile = compressImgUntil.saveBitmapToFile(compressBitmap,sharePreference.getString(CacheConfig.CACHE_USER_NAME));
        files.add(tempFile);

            if (newBitmap != null){
                finishUpdate();
            }

            newBitmap.recycle();
            compressBitmap.recycle();
        }



        if (requestCode == PermissionUtil.PERMISSION_TAG) {

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    PermissionUtil.showDialogTipUserGoToAppSettting(this);
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }


        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
    }

    class UpdateNickNameTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }
        @Override
        public void afterTextChanged(Editable editable) {

            nickName = String.valueOf(nickNameEdit.getText());

            if (!sharePreference.getString(CacheConfig.CACHE_NICKNMAE).equals(nickName)) {

                finishUpdate();
            }else {
                finishText.setClickable(false);
                finishText.setTextColor(getResources().getColor(R.color.gray1));
            }

        }
    }


    class UpdateIntroTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }
        @Override
        public void afterTextChanged(Editable editable) {


            introduce = String.valueOf(introduceEdit.getText());

            if (!sharePreference.getString(CacheConfig.CACHE_USER_INTRODUCTION_SELF).equals(introduce)) {

                finishUpdate();
            }else {
                finishText.setClickable(false);
                finishText.setTextColor(getResources().getColor(R.color.gray1));
            }

        }
    }

    private void finishUpdate() {

        finishText.setClickable(true);
        finishText.setTextColor(getResources().getColor(R.color.white));

        if (newBitmap == null) {
            files = null;
        }

        finishText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_SPINNER, true);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        upload();
                    }
                }, 1000);
            }
        });
    }

//    /**
//     * 删除单个文件
//     * @param   filePath    被删除文件的文件名
//     * @return 文件删除成功返回true，否则返回false
//     */
//    public boolean deleteFile(String filePath) {
//        File file = new File(filePath);
//        if (file.isFile() && file.exists()) {
//            return file.delete();
//        }
//        return false;
//    }



    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        PermissionUtil.showDialogTipUserGoToAppSettting(this);
                    } else {

                    }

                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


}
